<template>
  <div class="notification-management">
    <!-- 页面头部 -->
    <el-card class="header-card" shadow="never">
      <div class="page-header">
        <div class="header-left">
          <h1 class="page-title">
            <el-icon class="title-icon"><Message /></el-icon>
            我的信件推送管理
          </h1>
          <p class="page-desc">管理我的信件推送消息，支持定时发送和精准推送</p>
        </div>
        <div class="header-right">
          <el-button type="primary" size="large" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新建推送
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stats-card sent">
            <div class="stats-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ sentCount }}</div>
              <div class="stats-label">已发送</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stats-card pending">
            <div class="stats-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ pendingCount }}</div>
              <div class="stats-label">待发送</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stats-card draft">
            <div class="stats-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ draftCount }}</div>
              <div class="stats-label">草稿</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stats-card total">
            <div class="stats-icon">
              <el-icon><DataLine /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ totalCount }}</div>
              <div class="stats-label">总计</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <template #header>
        <div class="search-header">
          <span class="search-title">
            <el-icon><Search /></el-icon>
            筛选条件
          </span>
        </div>
      </template>
      <el-form :model="searchForm" inline class="search-form">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="推送标题">
              <el-input
                v-model="searchForm.title"
                placeholder="请输入推送标题"
                clearable
                prefix-icon="Search"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="推送渠道">
              <el-select v-model="searchForm.channel" placeholder="请选择渠道" clearable style="width: 120px">
                <el-option label="全部" value="" />
                <el-option label="站内信" value="station" />
                <el-option label="企业微信" value="wechat" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
                <el-option label="全部" value="" />
                <el-option label="已发送" value="sent" />
                <el-option label="待发送" value="pending" />
                <el-option label="草稿" value="draft" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 主要内容 -->
    <el-card class="main-content">
      <!-- 批量操作 -->
        <div class="table-toolbar">
          <div class="toolbar-left">
            <el-checkbox v-model="selectAll" @change="handleSelectAll" :indeterminate="isIndeterminate">全选</el-checkbox>
            <el-button
              type="danger"
              :disabled="selectedRows.length === 0"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button
              type="success"
              :disabled="selectedRows.length === 0"
              @click="handleBatchSend"
            >
              批量发送
            </el-button>
          </div>
          <div class="toolbar-right">
            <span class="selected-info">已选择 {{ selectedRows.length }} 项</span>
          </div>
        </div>

        <div class="table-container">
          <el-table
            :data="filteredNotifications"
            border
            stripe
            @selection-change="handleSelectionChange"
            v-loading="loading"
            height="100%"
          >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="channel" label="推送渠道" width="120">
          <template #default="scope">
            <div class="channel-tags">
              <el-tag
                v-for="ch in scope.row.channel"
                :key="ch"
                :type="getChannelTagType(ch)"
                size="small"
                style="margin: 2px;"
              >
                {{ channelMap[ch] }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="pushMethod" label="推送方式" width="150">
          <template #default="scope">
            <div class="push-method-tags">
              <el-tag
                v-for="method in scope.row.pushMethod"
                :key="method"
                :type="getPushMethodTagType(method)"
                size="small"
                style="margin: 2px;"
              >
                {{ pushMethodMap[method] }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="target" label="推送对象" width="120">
          <template #default="scope">
            <el-tag :type="getTargetTagType(scope.row.target)" size="small">
              {{ getTargetText(scope.row.target) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="pushTime" label="推送时间" width="160" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ statusMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="info" @click="handleView(scope.row)">详情</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.status === 'sent'">编辑</el-button>
              <el-button v-if="scope.row.status !== 'sent'" size="small" type="success" @click="handleSend(scope.row)">发送</el-button>
              <el-button v-if="scope.row.status === 'sent'" size="small" type="warning" @click="handleRecall(scope.row)">撤回</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="page.current"
            v-model:page-size="page.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalCount"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
    </el-card>

    <!-- 新建/编辑推送对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑推送' : '新建推送'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px" class="notification-form">
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="推送标题" prop="title" required>
              <el-input
                v-model="form.title"
                placeholder="请输入推送标题"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="推送渠道" prop="channel" required>
              <el-select
                v-model="form.channel"
                placeholder="请选择推送渠道"
                multiple
                style="width: 100%"
              >
                <el-option label="站内信" value="station" />
                <!-- <el-option label="企业微信" value="wechat" /> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推送方式" prop="pushMethod" required>
              <el-select
                v-model="form.pushMethod"
                multiple
                placeholder="请选择推送方式，支持多选"
                style="width: 100%"
                collapse-tags
                collapse-tags-tooltip
              >
                <el-option label="系统推送通知" value="system" />
                <el-option label="APP内顶部消息" value="app_top" />
                <el-option label="红点消息" value="red_dot" />
                <el-option label="弹窗提醒" value="popup" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="优先级">
              <el-select v-model="form.priority" style="width: 100%">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="推送内容" prop="content" required class="content-editor-form-item">
              <QuillEditor
                v-model:content="form.content"
                contentType="html"
                style="width: 100%;"
                :options="editorOptions"
                class="content-editor"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16" class="target-selection-row">
          <el-col :span="12">
            <el-form-item label="推送对象">
              <el-select v-model="form.target" style="width: 100%" @change="handleTargetChange">
                <el-option label="全部B端用户" value="all_b" />
                <el-option label="全部C端用户" value="all_c" />
                <el-option label="指定标签" value="tags" />
                <el-option label="指定用户" value="users" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送方式">
              <el-select v-model="form.sendType" style="width: 100%">
                <el-option label="立即发送" value="immediate" />
                <el-option label="定时发送" value="scheduled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 指定标签选择 -->
        <el-row :gutter="16" v-if="form.target === 'tags'">
          <el-col :span="24">
            <el-form-item label="选择标签" prop="selectedTags">
              <el-select
                v-model="form.selectedTags"
                multiple
                placeholder="请选择标签，支持多选"
                style="width: 100%"
                collapse-tags
                collapse-tags-tooltip
              >
                <el-option
                  v-for="tag in availableTags"
                  :key="tag.id"
                  :label="tag.name"
                  :value="tag.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 指定用户选择 -->
        <el-row :gutter="16" v-if="form.target === 'users'">
          <el-col :span="24">
            <el-form-item label="指定用户" prop="selectedUsers">
              <el-input
                v-model="form.selectedUsers"
                type="textarea"
                :rows="3"
                placeholder="请输入用户名或用户ID，多个用户请用换行或逗号分隔"
                style="width: 100%"
              />
              <div class="form-tip">
                支持输入用户名或用户ID，多个用户请用换行或逗号分隔
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16" v-if="form.sendType === 'scheduled'">
          <el-col :span="12">
            <el-form-item label="发送时间">
              <el-date-picker
                v-model="form.pushTime"
                type="datetime"
                placeholder="选择发送时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item>
              <el-checkbox v-model="form.retryOnFailure">失败重试</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button @click="openPreview">H5预览</el-button>
          <el-button @click="handleSaveDraft">保存草稿</el-button>
          <el-button type="primary" @click="handleSubmit">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- H5预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="H5预览效果"
      width="450px"
      :close-on-click-modal="true"
      center
    >
      <div class="preview-h5">
        <div class="preview-h5-shell">
          <div class="preview-h5-header">
            <div class="preview-title">{{ form.title || '推送标题' }}</div>
            <div class="preview-meta">
              <span class="preview-time">{{ dayjs().format('YYYY/M/D HH:mm:ss') }}</span>
            </div>
          </div>
          <div class="preview-content" v-html="form.content || '推送内容预览'"></div>
        </div>
      </div>

      <template #footer>
        <el-button @click="previewVisible = false">关闭预览</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="推送详情"
      width="800px"
      :close-on-click-modal="true"
    >
      <div v-if="currentDetail" class="detail-content">
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="推送标题">{{ currentDetail.title }}</el-descriptions-item>
            <el-descriptions-item label="推送ID">{{ currentDetail.id }}</el-descriptions-item>
            <el-descriptions-item label="推送渠道">
              <el-tag
                v-for="ch in currentDetail.channel"
                :key="ch"
                :type="getChannelTagType(ch)"
                size="small"
                style="margin-right: 4px;"
              >
                {{ channelMap[ch] }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="推送方式">
              <div class="push-method-tags">
                <el-tag
                  v-for="method in currentDetail.pushMethod"
                  :key="method"
                  :type="getPushMethodTagType(method)"
                  size="small"
                  style="margin-right: 4px;"
                >
                  {{ pushMethodMap[method] }}
                </el-tag>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="推送对象">
              <el-tag :type="getTargetTagType(currentDetail.target)" size="small">
                {{ getTargetText(currentDetail.target) }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="推送时间">{{ currentDetail.pushTime }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(currentDetail.status)" size="small">
                {{ statusMap[currentDetail.status] }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentDetail.createdAt }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ currentDetail.updatedAt }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section" v-if="currentDetail.target === 'tags' && currentDetail.selectedTags?.length">
          <h3>选择的标签</h3>
          <div class="tag-list">
            <el-tag
              v-for="tagId in currentDetail.selectedTags"
              :key="tagId"
              type="warning"
              size="small"
              style="margin-right: 8px; margin-bottom: 8px;"
            >
              {{ getTagName(tagId) }}
            </el-tag>
          </div>
        </div>

        <div class="detail-section" v-if="currentDetail.target === 'users' && currentDetail.selectedUsers">
          <h3>指定用户</h3>
          <div class="user-list">
            {{ currentDetail.selectedUsers }}
          </div>
        </div>

        <div class="detail-section">
          <h3>推送内容</h3>
          <div class="content-preview" v-html="currentDetail.content"></div>
        </div>

        <div class="detail-section" v-if="currentDetail.stats">
          <h3>推送统计</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="发送数量">{{ currentDetail.stats.sent }}</el-descriptions-item>
            <el-descriptions-item label="阅读数量">{{ currentDetail.stats.read }}</el-descriptions-item>
            <el-descriptions-item label="阅读率">
              {{ ((currentDetail.stats.read / currentDetail.stats.sent) * 100).toFixed(1) }}%
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
  Plus, Check, Clock, Document, DataLine, Search, Refresh, Message
} from '@element-plus/icons-vue'

interface Notification {
  id: number
  title: string
  content: string
  channel: string[]
  pushMethod: string[]
  target: string
  targetGroups?: string[]
  tags?: string[]
  selectedTags?: string[]
  selectedUsers?: string
  pushTime: string
  status: string
  sendType: string
  retryOnFailure: boolean
  createdAt: string
  updatedAt: string
  stats?: {
    sent: number
    read: number
  }
}



// 映射配置
const channelMap: { [key: string]: string } = {
  station: '站内信',
  wechat: '企业微信',
}

const statusMap: { [key: string]: string } = {
  sent: '已发送',
  pending: '待发送',
  draft: '草稿',
  recalled: '已撤回'
}



const pushMethodMap: { [key: string]: string } = {
  system: '系统推送通知',
  app_top: 'APP内顶部消息',
  red_dot: '红点消息',
  popup: '弹窗提醒'
}

const targetMap: { [key: string]: string } = {
  all_b: '全部B端用户',
  all_c: '全部C端用户',
  tags: '指定标签',
  users: '指定用户'
}

// 基础数据
const loading = ref(false)

// 富文本编辑器配置
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image']
    ]
  }
}

// 搜索表单
const searchForm = reactive({
  title: '',
  channel: '',
  status: '',
  dateRange: [] as Date[]
})

// 分页
const page = reactive({
  current: 1,
  size: 10
})

// 选择相关
const selectAll = ref(false)
const selectedRows = ref<Notification[]>([])
const isIndeterminate = computed(() => {
  const length = selectedRows.value.length
  return length > 0 && length < filteredNotifications.value.length
})

// Mock 数据
const notifications = ref<Notification[]>([
  {
    id: 1,
    title: '系统升级通知',
    content: '<p>系统将于今晚22:00-24:00进行升级，请提前做好准备。</p>',
    channel: ['station'],
    pushMethod: ['system', 'app_top'],
    target: 'all_b',
    targetGroups: [],
    tags: [],
    selectedTags: [],
    selectedUsers: '',

    pushTime: '2024-07-01 22:00:00',
    status: 'sent',
    sendType: 'scheduled',
    retryOnFailure: true,
    createdAt: '2024-07-01 10:00:00',
    updatedAt: '2024-07-01 10:00:00',
    stats: { sent: 1250, read: 980 }
  },
  {
    id: 2,
    title: '【优惠活动】夏季大促销',
    content: '<h2>夏季大促活动即将开始</h2><p>全场商品五折起！</p>',
    channel: ['station'],
    pushMethod: ['system', 'red_dot'],
    target: 'all_c',
    targetGroups: ['b_member', 'c_member'],
    tags: [],
    selectedTags: [],
    selectedUsers: '',
    pushTime: '2024-07-05 10:00:00',
    status: 'pending',
    sendType: 'scheduled',
    retryOnFailure: true,
    createdAt: '2024-07-04 15:30:00',
    updatedAt: '2024-07-04 15:30:00'
  },
  {
    id: 3,
    title: '新功能上线提醒',
    content: '<p>新功能"一键下单"已正式上线！</p>',
    channel: ['station'],
    pushMethod: ['app_top'],
    target: 'tags',
    targetGroups: [],
    tags: ['高价值用户', '活跃用户'],
    selectedTags: ['tag1', 'tag2'],
    selectedUsers: '',
    pushTime: '2024-07-10 09:00:00',
    status: 'draft',
    sendType: 'immediate',
    retryOnFailure: false,
    createdAt: '2024-07-09 14:20:00',
    updatedAt: '2024-07-09 16:45:00'
  },
  {
    id: 4,
    title: '用户活动通知',
    content: '<p>感谢您的参与，活动奖励已发放到您的账户。</p>',
    channel: ['station'],
    pushMethod: ['system', 'popup'],
    target: 'users',
    targetGroups: [],
    tags: [],
    selectedTags: [],
    selectedUsers: 'user001,user002,张三',
    pushTime: '2024-07-15 14:30:00',
    status: 'sent',
    sendType: 'immediate',
    retryOnFailure: true,
    createdAt: '2024-07-15 14:25:00',
    updatedAt: '2024-07-15 14:25:00',
    stats: { sent: 3, read: 2 }
  }
])

// 可用标签数据
const availableTags = ref([
  { id: 'tag1', name: 'VIP用户', color: '#409eff' },
  { id: 'tag2', name: '活跃用户', color: '#67c23a' },
  { id: 'tag3', name: '新用户', color: '#e6a23c' },
  { id: 'tag4', name: '高价值用户', color: '#f56c6c' },
  { id: 'tag5', name: '企业用户', color: '#909399' }
])

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const previewVisible = ref(false)
const detailVisible = ref(false)
const currentDetail = ref<Notification | null>(null)
const form = ref({
  id: -1,
  title: '',
  content: '',
  channel: [] as string[],
  pushMethod: [] as string[],
  target: 'all_b',
  targetGroups: [] as string[],
  tags: [] as string[],
  selectedTags: [] as string[],
  selectedUsers: '',

  pushTime: '',
  status: 'draft',
  sendType: 'immediate',
  retryOnFailure: true
})

const formRules = {
  title: [{ required: true, message: '请输入推送标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入推送内容', trigger: 'blur' }],
  channel: [
    {
      required: true,
      type: 'array',
      min: 1,
      message: '请选择至少一个推送渠道',
      trigger: 'change'
    }
  ],
  pushMethod: [{ required: true, message: '请选择推送方式', trigger: 'change' }],
  pushTime: [{ required: true, message: '请选择推送时间', trigger: 'change' }]
}

const formRef = ref()

// 计算属性
const sentCount = computed(() => notifications.value.filter(n => n.status === 'sent').length)
const pendingCount = computed(() => notifications.value.filter(n => n.status === 'pending').length)
const draftCount = computed(() => notifications.value.filter(n => n.status === 'draft').length)
const totalCount = computed(() => notifications.value.length)

const filteredNotifications = computed(() => {
  let result = notifications.value

  if (searchForm.title) {
    result = result.filter(n => n.title.includes(searchForm.title))
  }

  if (searchForm.channel) {
    result = result.filter(n => n.channel.includes(searchForm.channel))
  }

  if (searchForm.status) {
    result = result.filter(n => n.status === searchForm.status)
  }

  // 按推送时间倒序排序
  return result.sort((a, b) => {
    const timeA = new Date(a.pushTime).getTime()
    const timeB = new Date(b.pushTime).getTime()
    return timeB - timeA // 倒序排序
  })
})

// 工具函数
function getChannelTagType(channel: string) {
  return channel === 'station' ? 'primary' : 'success'
}

function getPushMethodTagType(pushMethod: string) {
  const typeMap: { [key: string]: string } = {
    system: 'primary',
    app_top: 'success',
    red_dot: 'danger',
    popup: 'warning'
  }
  return typeMap[pushMethod] || ''
}



function getStatusTagType(status: string) {
  const typeMap: { [key: string]: string } = {
    sent: 'success',
    pending: 'warning',
    draft: 'info',
    recalled: 'danger'
  }
  return typeMap[status] || ''
}

function getTargetText(target: string) {
  return targetMap[target] || target
}

function getTargetTagType(target: string) {
  const typeMap: { [key: string]: string } = {
    all_b: 'primary',
    all_c: 'success',
    tags: 'warning',
    users: 'info'
  }
  return typeMap[target] || ''
}

// 事件处理函数
function handleAdd() {
  isEdit.value = false
  form.value = {
    id: -1,
    title: '',
    content: '',
    channel: [],
    pushMethod: [],
    target: 'all_b',
    targetGroups: [],
    tags: [],
    selectedTags: [],
    selectedUsers: '',

    pushTime: dayjs().add(1, 'hour').format('YYYY-MM-DD HH:mm:ss'),
    status: 'draft',
    sendType: 'immediate',
    retryOnFailure: true
  }
  dialogVisible.value = true
}

function handleEdit(row: Notification) {
  isEdit.value = true
  form.value = {
    ...row,
    targetGroups: row.targetGroups || [],
    tags: row.tags || [],
    selectedTags: row.selectedTags || [],
    selectedUsers: row.selectedUsers || ''
  }
  dialogVisible.value = true
}

// 处理推送对象变化
function handleTargetChange() {
  // 清空相关字段
  form.value.selectedTags = []
  form.value.selectedUsers = ''
}

// H5预览
function openPreview() {
  if (!form.value.title) {
    ElMessage.warning('请先输入推送标题')
    return
  }
  if (!form.value.content) {
    ElMessage.warning('请先输入推送内容')
    return
  }
  previewVisible.value = true
}

// 获取标签名称
function getTagName(tagId: string) {
  const tag = availableTags.value.find(t => t.id === tagId)
  return tag ? tag.name : tagId
}

function handleView(row: Notification) {
  currentDetail.value = row
  detailVisible.value = true
}

function handleSend(row: Notification) {
  ElMessageBox.confirm(`确定要发送推送【${row.title}】吗？`, '提示', {
    type: 'warning',
  }).then(() => {
    row.status = 'sent'
    row.stats = { sent: Math.floor(Math.random() * 1000) + 100, read: Math.floor(Math.random() * 800) + 50 }
    ElMessage.success('发送成功')
  })
}

function handleDelete(row: Notification) {
  ElMessageBox.confirm(`确定要删除推送【${row.title}】吗？`, '提示', {
    type: 'warning',
  }).then(() => {
    const index = notifications.value.findIndex(n => n.id === row.id)
    if (index !== -1) {
      notifications.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

function handleSearch() {
  // 搜索逻辑已在计算属性中实现
  ElMessage.success('搜索完成')
}

function handleReset() {
  searchForm.title = ''
  searchForm.channel = ''
  searchForm.status = ''
  searchForm.dateRange = []
  ElMessage.success('重置完成')
}

function handleSelectAll(val: boolean) {
  if (val) {
    selectedRows.value = [...filteredNotifications.value]
  } else {
    selectedRows.value = []
  }
}

function handleSelectionChange(selection: Notification[]) {
  selectedRows.value = selection
  selectAll.value = selection.length === filteredNotifications.value.length
}

function handleBatchDelete() {
  if (selectedRows.value.length === 0) return

  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条推送吗？`, '提示', {
    type: 'warning',
  }).then(() => {
    const selectedIds = selectedRows.value.map(row => row.id)
    notifications.value = notifications.value.filter(n => !selectedIds.includes(n.id))
    selectedRows.value = []
    selectAll.value = false
    ElMessage.success('批量删除成功')
  })
}

function handleBatchSend() {
  if (selectedRows.value.length === 0) return

  const canSendRows = selectedRows.value.filter(row => row.status !== 'sent')
  if (canSendRows.length === 0) {
    ElMessage.warning('选中的推送都已发送')
    return
  }

  ElMessageBox.confirm(`确定要发送选中的 ${canSendRows.length} 条推送吗？`, '提示', {
    type: 'warning',
  }).then(() => {
    canSendRows.forEach(row => {
      row.status = 'sent'
      row.stats = { sent: Math.floor(Math.random() * 1000) + 100, read: Math.floor(Math.random() * 800) + 50 }
    })
    selectedRows.value = []
    selectAll.value = false
    ElMessage.success('批量发送成功')
  })
}

function handleSaveDraft() {
  if (!formRef.value) return

  formRef.value.validate((valid: boolean) => {
    if (valid) {
      form.value.status = 'draft'
      handleSubmit()
    }
  })
}

function handleSubmit() {
  if (!formRef.value) {
    console.error('formRef is not available')
    return
  }

  formRef.value.validate((valid: boolean, fields: any) => {
    if (valid) {
      if (isEdit.value) {
        const index = notifications.value.findIndex(n => n.id === form.value.id)
        if (index !== -1) {
          const existingItem = notifications.value[index]
          notifications.value[index] = {
            ...existingItem,
            ...form.value,
            updatedAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
          }
        }
      } else {
        notifications.value.push({
          ...form.value,
          id: Date.now(),
          createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          updatedAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
        })
      }
      dialogVisible.value = false
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    } else {
      console.error('表单验证失败:', fields)
      ElMessage.error('请检查表单填写是否正确')
    }
  })
}

function handleRecall(row: Notification) {
  ElMessageBox.confirm(`确定要撤回推送【${row.title}】吗？`, '提示', {
    type: 'warning',
  }).then(() => {
    row.status = 'recalled'
    ElMessage.success('撤回成功')
  })
}
</script>

<style scoped>
.notification-management {
  padding: 16px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

/* 页面头部样式 */
.header-card {
  margin-bottom: 16px;
  border-radius: 12px;
  border: none;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  color: #409eff;
  font-size: 24px;
}

.page-desc {
  color: #606266;
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 16px;
}

.stats-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #f0f0f0;
  height: 80px;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px 0 rgba(0, 0, 0, 0.1);
}

.stats-card .stats-icon {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 18px;
  color: white;
  flex-shrink: 0;
}

.stats-card.sent .stats-icon {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stats-card.pending .stats-icon {
  background: linear-gradient(135deg, #e6a23c, #f0a020);
}

.stats-card.draft .stats-icon {
  background: linear-gradient(135deg, #909399, #b1b3b8);
}

.stats-card.total .stats-icon {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 2px;
}

.stats-label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 16px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

/* 主要内容样式 */
.main-content {
  margin-top: 0;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 确保卡片完全对齐 */
.search-card,
.main-content {
  margin-left: 0;
  margin-right: 0;
  width: 100%;
  box-sizing: border-box;
}

/* 确保卡片内容对齐 */
:deep(.search-card .el-card__body) {
  padding: 20px;
}

:deep(.search-card .el-card__header) {
  padding: 20px 20px 0 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.main-content .el-card__body) {
  padding: 0;
}

.search-header {
  display: flex;
  align-items: center;
}

.search-title {
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 6px;
}

.search-form {
  margin-top: 8px;
}

.search-form .el-form-item {
  margin-bottom: 16px;
}

.search-form .el-input,
.search-form .el-select {
  width: 100%;
}

/* 主要内容样式 */
.main-content {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 20px 20px 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selected-info {
  color: #606266;
  font-size: 14px;
  background: #f8f9fa;
  padding: 4px 12px;
  border-radius: 16px;
  border: 1px solid #e9ecef;
}

.channel-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.action-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: nowrap;
  align-items: center;
}

.action-buttons .el-button {
  flex-shrink: 0;
  min-width: auto;
  padding: 4px 8px;
  font-size: 12px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 20px 20px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  flex: 1;
}

:deep(.el-table th) {
  background: #fafbfc;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
  height: 50px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f5f7fa;
  height: 60px;
  padding: 12px 0;
}

:deep(.el-table tr:hover > td) {
  background: #f8f9fa;
}

:deep(.el-table .el-table__body-wrapper) {
  min-height: 400px;
  max-height: calc(100vh - 400px);
  overflow-y: auto;
}

/* 富文本编辑器样式 */
:deep(.ql-editor) {
  min-height: 200px;
  border-radius: 6px;
}

.editor-form-item :deep(.el-form-item__label) {
  align-self: flex-start;
  padding-top: 10px;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: 1px solid #f0f0f0;
}

.notification-form .el-form-item {
  margin-bottom: 20px;
}

/* 推送内容编辑器特殊间距 */
.content-editor-form-item {
  margin-bottom: 50px !important;
}

.content-editor {
  margin-bottom: 20px;
}

.notification-form .el-textarea__inner {
  resize: vertical;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 富文本编辑器样式 */
:deep(.ql-editor) {
  min-height: 200px;
  max-height: 350px;
  overflow-y: auto;
  font-size: 14px;
  line-height: 1.6;
}

:deep(.ql-container) {
  min-height: 200px;
  margin-bottom: 0;
}

:deep(.ql-toolbar) {
  border-top: 1px solid #e4e7ed;
  border-left: 1px solid #e4e7ed;
  border-right: 1px solid #e4e7ed;
  border-bottom: none;
  border-radius: 6px 6px 0 0;
  background-color: #fafbfc;
}

:deep(.ql-container) {
  border-left: 1px solid #e4e7ed;
  border-right: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
  border-top: none;
  border-radius: 0 0 6px 6px;
  min-height: 200px;
  margin-bottom: 20px;
}

:deep(.ql-editor.ql-blank::before) {
  color: #c0c4cc;
  font-style: normal;
}

:deep(.ql-snow .ql-tooltip) {
  z-index: 9999;
}

/* 富文本编辑器容器间距 */
.quill-editor {
  margin-bottom: 24px;
}

/* 确保富文本编辑器与下方内容的间距 */
:deep(.content-editor-form-item .el-form-item__content) {
  margin-bottom: 24px;
}

/* 富文本编辑器整体容器 */
:deep(.content-editor) {
  margin-bottom: 24px !important;
}

/* 推送对象选择行的上边距 */
.target-selection-row {
  margin-top: 30px;
}

/* H5预览样式 - 参考系统公告设计 */
.preview-h5 {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 400px;
  padding: 24px;
  background: #f8f9fa;
}

.preview-h5-shell {
  width: 375px;
  min-height: 600px;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.12);
  padding: 24px 20px;
  border: 2px solid #e9ecef;
  position: relative;
  overflow: hidden;
}

.preview-h5-shell::before {
  content: '';
  position: absolute;
  top: 8px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 4px;
  background: #bdc3c7;
  border-radius: 2px;
}

.preview-h5-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ecf0f1;
}

.preview-h5 .preview-title {
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
  text-align: center;
  margin-bottom: 8px;
  line-height: 1.4;
}

.preview-h5 .preview-meta {
  text-align: center;
  font-size: 12px;
  color: #7f8c8d;
}

.preview-time {
  color: #95a5a6;
}

.preview-content {
  font-size: 16px;
  color: #2c3e50;
  line-height: 1.8;
  word-break: break-word;
  min-height: 120px;
}

.preview-content :deep(h1),
.preview-content :deep(h2),
.preview-content :deep(h3) {
  color: #2c3e50;
  margin: 20px 0 12px 0;
}

.preview-content :deep(p) {
  margin: 12px 0;
}

.preview-content :deep(ul),
.preview-content :deep(ol) {
  margin: 12px 0;
  padding-left: 20px;
}

.preview-content :deep(li) {
  margin: 6px 0;
}

/* 详情页样式 */
.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  border-bottom: 2px solid #e9ecef;
  padding-bottom: 8px;
}

.content-preview {
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  min-height: 100px;
  font-size: 14px;
  line-height: 1.6;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.user-list {
  padding: 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
}

/* 推送方式标签样式 */
.push-method-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 内容预览对话框样式 */
:deep(.content-preview-dialog) {
  width: 600px;
}

:deep(.content-preview-dialog .el-message-box__message) {
  padding: 0;
}

/* 表单提示样式 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

:deep(.content-preview-dialog .el-message-box__content) {
  padding: 20px 20px 10px 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-section .el-col {
    margin-bottom: 16px;
  }

  .search-form .el-col {
    margin-bottom: 12px;
  }
}

@media (max-width: 768px) {
  .notification-management {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .stats-section .el-col {
    width: 50%;
  }

  .search-form .el-col {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>